#突破首板  "JobID": "7"
import pandas as pd
import json
from hqchartpy2_fast import FastHQChart, IHQData
import time
import sys
from utils.RedisUtil import warringResultToRedis
from value_cache.glabalVal import cacheValue
from datetime import datetime
# cacheValue.STOCK_LIST = []  # 股票列表
# cacheValue.CAPITAL_LIST = []  # 流通股本列表
def fuc_run():
    runConfig = {
        # 系统指标名字
        # "Name":"MA",
        # 执行的脚本
        "Script": '''
            X_1:=WINNER(CLOSE)*100;
            X_3:=BARSLASTCOUNT(CLOSE>=ZTPRICE(REF(CLOSE,1),0.096) AND CLOSE=HIGH)=1;
            XG:X_1>=60 AND X_1<=100 AND X_3=1;
            ''',
        # 脚本参数
        # "Args":[ { "Name": 'N1', "Value": 5 },{ "Name": 'N2', "Value": 10 },{ "Name": 'N3', "Value": 15 } ],
        "Args": [{"Name": "N", "Value": 1}, {"Name": "N1", "Value": 3}, {"Name": "N2", "Value": 20},{"Name": "N3", "Value": 4}],
        # 周期 复权
        "Period": 0, "Right": 0,
        # 股票池
        "Symbol": [],
        # 并行计算加速模式
        "Mode": {"Thread": False, "MinRunCount": 1000, "Count": 5},
        # 输出数据个数 如果只需要最后几个数据可以填几个的个数, 数据从最后开始返回的, 如1=返回最后1个数据 2=返回最后2个数组,  -1=返回所有的数据
        "OutCount": 1,
        # 单个股票执行完是否立即清空缓存, 更具K线个数配置, 不清空缓存到占用很多内存
        "ClearCache": True,

        "JobID": "7"
        # 获利盘:MA(WINNER(CLOSE),3) * 100 ;
    }

    # 加载股票列表到配置中
    for i in cacheValue.STOCK_LIST:
        runConfig["Symbol"].append(i)

    # sourceUrl = 'data\mfinancial_data\mfinancial.csv';
    # Cap_Df = pd.read_csv(sourceUrl)
    # mDict = Cap_Df.set_index('ths_thscode_stock').T.to_dict('list')
    # cacheValue.CAPITAL_LIST.append(mDict)

    jsConfig = json.dumps(runConfig)  # 运行配置项
    hqData = HQChartData()  # 实例化数据类
    result = HQResultTest()  # 实例计算结果接收类
    result.IsOutLog = False

    start = time.process_time()
    res = FastHQChart.Run(jsConfig, hqData, proSuccess=result.RunSuccess, procFailed=result.RunFailed)
    elapsed = (time.process_time() - start)
    log = "突破首板  Time used:{0}, 股票个数:{1}".format(elapsed, len(runConfig['Symbol']))
    #设置返回结果
    now = datetime.now()  # 当前时间
    strnow = datetime.strftime(now, '%Y%m%d')
    mResult = {'FncName': "突破首板", 'Data': result.Result, 'Fnc_type': 7,'Date':strnow}
    print('突破首板  选股完毕')
    warringResultToRedis(7, mResult,"flsg")

class HQResultTest():
    def __init__(self):
        self.Result = []  # 保存所有的执行结果
        self.IsOutLog = True  # 是否输出日志
        self.count = 0

    # 执行成功回调
    def RunSuccess(self, symbol, jsData, jobID):
        # self.Result.append({"Symbol":symbol, "Data":jsData})  # 保存结果

        try:
            jsonResult = json.loads(jsData)
            if (jsonResult['OutVar'][0]['Data'][0] is None):
                return
            else:
                if (jsonResult['OutVar'][0]['Data'][0] == 1.0):
                    fun_name = ''
                    now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
                    self.Result.append({"Symbol": symbol, "StockName": cacheValue.CAPITAL_LIST[0][symbol][2], "Fnc_type": 7,
                                        "DateTime": now_time, "Fnc_name": "突破首板 "})  # 保存符合条件的股票结果
                    self.count = self.count + 1

            if (self.IsOutLog):
                log = "{0} success".format(symbol)
                print(log)
                print(jsData)

        except Exception as e:
            print(e)

    # 执行失败回调
    def RunFailed(self, code, symbol, error, jobID):
        # print(symbol)
        log = "{0}\n{1} failed\n{2}".format(code, symbol, error)
        print(log)


class HQChartData(IHQData):
    def __init__(self):
        pass

    def GetKLineData(self, symbol, period, right, jobID):
        if (symbol in cacheValue.Cache):
            return cacheValue.Cache[symbol]
    def GetFinance(self, symbol, id, period, right, kcount, jobID):
        pyCacheData = []
        for i in range(kcount):  # 生成财务数据
            pyCacheData.append(8976549.994 + i)

        data = {"type": 1, "data": pyCacheData}
        return data

    def GetDynainfo(self, symbol, id, period, right, kcount, jobID):
        data = {"type": 0, "data": 5}
        return data

    def GetCapital(self, symbol, period, right, kcount, jobID):
        #返回流通盘数据
        data = {"type": 0, "data": cacheValue.CAPITAL_LIST[0][symbol][1]}
        return data

    # 历史所有的流通股
    def GetHisCapital(self, symbol, period, right, kcount, jobID):
        pyCacheData = []
        for i in range(kcount):  # 生成流通股数据
            if symbol in cacheValue.CAPITAL_LIST[0]:
                pyCacheData.append(cacheValue.CAPITAL_LIST[0][symbol][1])
            else:
                pyCacheData.append(1000000)
        data = {"type": 1, "data": pyCacheData}
        return data

    # 大盘数据
    def GetIndex(self, symbol, varName, period, right, kcount, jobID):
        if (varName == u'INDEXA'):  # 大盘成交额
            pass
        elif (varName == u'INDEXC'):  # 大盘收盘价
            pass
        elif (varName == u'INDEXH'):  # 大盘最高价
            pass
        elif (varName == u'INDEXL'):  # 大盘最低价
            pass
        elif (varName == u'INDEXO'):  # 大盘开盘价
            pass
        elif (varName == u'INDEXV'):  # 大盘成交量
            pass
        elif (varName == u'INDEXADV'):  # 上涨家数
            pass
        elif (varName == u'INDEXDEC'):  # 下跌家数
            pass

        # 测试数据
        pyCacheData = []
        for i in range(kcount):
            pyCacheData.append(2888.8 + i)
        data = {"type": 1, "data": pyCacheData}
        return data

    #